package com.openroom.ui.component;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pivot.beans.BXML;
import org.apache.pivot.collections.Map;
import org.apache.pivot.util.Resources;
import org.apache.pivot.wtk.BoxPane;
import org.apache.pivot.wtk.Button;
import org.apache.pivot.wtk.ButtonPressListener;
import org.apache.pivot.wtk.ImageView;
import org.apache.pivot.wtk.Label;
import org.apache.pivot.wtk.LinkButton;
import org.apache.pivot.wtk.Slider;
import org.apache.pivot.wtk.SliderValueListener;
import org.apache.pivot.wtk.TextInput;
import org.apache.pivot.wtk.TextInputContentListener;
import org.apache.pivot.wtk.media.Picture;

import com.jphotomanager.io.ImageLibrary;
import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.ModelLocator;
import com.openroom.model.Photograph;
import com.openroom.ui.MainWindow;
import com.openroom.ui.NamespaceHelper;

public class ThumbnailPreviewPane extends BoxPane {

    @BXML
    private ImageView tnailPreviewImage;
    @BXML
    private ImageView tnailPreviewImage1;
    @BXML
    private Label fileNameLabel;
    @BXML
    private Slider exposureSlider;
    @BXML
    private Slider brightnessSlider;
    @BXML
    private Slider shadowsSlider;
    @BXML
    private Slider contrastSlider;

    private static boolean sliderMode = false;

    public void initialize(Map<String, Object> namespace, URL arg1,
            Resources arg2) {
        NamespaceHelper.initialize(namespace, this);
        ((ZoomablePreviewImage) tnailPreviewImage1).initialize(namespace, arg1,
                arg2, null);
        EventManager.getInstance().listenToEventType(
                EventType.CURRENT_IMAGE_CHANGED, new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        Photograph photograph = ModelLocator.getInstance()
                                .getCurrentlySelectedImage();
                        if (photograph == null) {
                            fileNameLabel.setText("");
                            URL nodeResource = MainWindow.class
                                    .getClassLoader().getResource(
                                            "com/openroom/ui/noImage.png");
                            tnailPreviewImage.setImage(nodeResource);
                            tnailPreviewImage1.setImage(nodeResource);
                            return;
                        }
                        fileNameLabel.setText(photograph.getFileName());
                        try {
                            if (photograph.getPreviewImagePath() != null) {
                                try {
                                    Picture image = new Picture(ImageIO
                                            .read(new File(photograph
                                                    .getPreviewImagePath())));
                                    tnailPreviewImage.setImage(image);
                                    tnailPreviewImage1.setImage(image);
                                } catch (Exception e) {
                                    photograph.setPreviewImagePath(null);
                                    Picture image1 = new Picture(ImageIO
                                            .read(new File(photograph
                                                    .getThumbnailPath())));
                                    tnailPreviewImage.setImage(image1);
                                    tnailPreviewImage1.setImage(image1);
                                }
                            } else if (photograph.getThumbnailPath() != null) {
                                Picture image = new Picture(ImageIO
                                        .read(new File(photograph
                                                .getThumbnailPath())));
                                tnailPreviewImage.setImage(image);
                                tnailPreviewImage1.setImage(image);
                            } else {
                                URL nodeResource = MainWindow.class
                                        .getClassLoader().getResource(
                                                "com/openroom/ui/noImage.png");
                                tnailPreviewImage.setImage(nodeResource);
                                tnailPreviewImage1.setImage(nodeResource);
                            }
                            tnailPreviewImage.invalidate();
                            tnailPreviewImage.validate();
                            tnailPreviewImage1.invalidate();
                            tnailPreviewImage1.validate();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

        exposureSlider.getSliderValueListeners().add(new SliderValueListener() {
            @Override
            public void valueChanged(Slider slider, int previousValue) {
                sliderMode = true;
                ((TextInput) exposureSlider.getParent().get(1)).setText(""
                        + slider.getValue());
                ImageLibrary.getInstance().setExposure(slider.getValue());
                EventManager.getInstance().publishEvent(
                        new ApplicationEvent(EventType.RELOAD_IMAGE));
            }
        });

        ((LinkButton) exposureSlider.getParent().get(2))
                .getButtonPressListeners().add(new ButtonPressListener() {
                    @Override
                    public void buttonPressed(Button button) {
                        exposureSlider.setValue(0);
                    }
                });
        ((TextInput) exposureSlider.getParent().get(1))
                .getTextInputContentListeners().add(
                        new TextInputContentListener.Adapter() {
                            @Override
                            public void textInserted(TextInput textInput,
                                    int index, int count) {
                                validateText(textInput);
                            }

                            private boolean validateText(TextInput textInput) {
                                try {
                                    if (textInput.getText() == null
                                            || textInput.getText().isEmpty()
                                            || textInput.getText().length() == 0)
                                        return true;
                                    int parseInt = Integer.parseInt(textInput
                                            .getText());
                                    if (parseInt < exposureSlider.getStart()
                                            || parseInt > exposureSlider
                                                    .getEnd()) {
                                        textInput.setText(""
                                                + exposureSlider.getValue());
                                    } else
                                        return true;
                                } catch (Exception e) {
                                    textInput.setText(""
                                            + exposureSlider.getValue());
                                }
                                return false;
                            }

                            @Override
                            public void textChanged(TextInput textInput) {
                                if (!sliderMode) {
                                    if (validateText(textInput)) {
                                        exposureSlider.setValue(Integer
                                                .parseInt("0"
                                                        + textInput.getText()));
                                    }
                                }
                                sliderMode = false;
                            }
                        });
        shadowsSlider.getSliderValueListeners().add(new SliderValueListener() {
            @Override
            public void valueChanged(Slider slider, int previousValue) {
                sliderMode = true;
                ((TextInput) shadowsSlider.getParent().get(1)).setText(""
                        + slider.getValue());
                ImageLibrary.getInstance().setShadows(slider.getValue());
                EventManager.getInstance().publishEvent(
                        new ApplicationEvent(EventType.RELOAD_IMAGE));
            }
        });

        brightnessSlider.getSliderValueListeners().add(new SliderValueListener() {
            
            @Override
            public void valueChanged(Slider slider, int previousValue) {
                ImageLibrary.getInstance().adjustBrightness(slider.getValue());
                EventManager.getInstance().publishEvent(
                        new ApplicationEvent(EventType.RELOAD_IMAGE));
            }
        });
        
        contrastSlider.getSliderValueListeners().add(new SliderValueListener() {
            @Override
            public void valueChanged(Slider slider, int previousValue) {
                sliderMode = true;
                ((TextInput) contrastSlider.getParent().get(1)).setText(""
                        + slider.getValue());
                ImageLibrary.getInstance().setContrast(slider.getValue());
                EventManager.getInstance().publishEvent(
                        new ApplicationEvent(EventType.RELOAD_IMAGE));
            }
        });
        
        ((LinkButton) shadowsSlider.getParent().get(2))
                .getButtonPressListeners().add(new ButtonPressListener() {
                    @Override
                    public void buttonPressed(Button button) {
                        shadowsSlider.setValue(0);
                    }
                });
        ((LinkButton) contrastSlider.getParent().get(2))
        .getButtonPressListeners().add(new ButtonPressListener() {
            @Override
            public void buttonPressed(Button button) {
                contrastSlider.setValue(0);
            }
        });
        EventManager.getInstance().listenToEventType(EventType.IMAGE_IMPORTED,
                new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        List<Photograph> allPhotographsOfFolder = ModelLocator
                                .getInstance().getAllShowingImage();
                        int lastImageCounter = allPhotographsOfFolder.size() - 1;
                        try {
                            Photograph p = allPhotographsOfFolder
                                    .get(lastImageCounter);
                            tnailPreviewImage.setImage(new Picture(ImageIO
                                    .read(new File(p.getThumbnailPath()))));
                            fileNameLabel.setText(p.getFileName());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

        EventManager.getInstance().listenToEventType(
                EventType.CURRENT_IMAGE_CHANGED, new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        exposureSlider.setValue(0);
                        shadowsSlider.setValue(0);
                    }
                });
    }
}
